﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using Isis.Interfaces;
using Isis.Model;
using Isis.Views;

namespace Isis.Controllers
{
    /// <summary>
    /// DataController is used to provide data to jQuery callbacks, in JSON format
    /// The Trace view will optionally use a tabbed UI to display the contents of the ASP.NET trace output (the last tab will be Full or All and will show all sections)
    /// The Data response should never use the default UI for Isis since it's returning only DATA
    /// </summary>
    public class DataController : IControlPanelController
    {
        private readonly string _basePath;

        public DataController(string basePath)
        {
            _basePath = basePath;
        }

        public ControllerTab Tab
        {
            get { return null; }
        }

        public string Action { get; set; }

        public string Parameter { get; set; }

        public IEnumerable<string> SubTabs
        {
            get { return new string[0]; }
        }

        public void Render(TextWriter writer)
        {
            writer.Write("Data Request<br />Action: " + this.Action + "<br />Parameter: " + this.Parameter + "<br />");
            if (this.Action.ToLower() == "traceindex")
            {
                RenderTraceIndex(writer, this.Parameter);
            }
        }

        private void RenderTraceIndex(TextWriter writer, string parameter)
        {
            writer.Write("Rendering Trace Data for Parameter " + this.Parameter + "<br />");
            var requestParams = this.Parameter.Split(';');
            var index = Int32.Parse(requestParams[0]);
            var subindex = Int32.Parse(requestParams[1]);
            writer.Write("Index: " + index + " Subindex: " + subindex + "<br />");

            var dataset = (DataSet)TraceAdapter.GetData()[index];
            var datatable = dataset.Tables[subindex];
            writer.Write(datatable.TableName + "<br />");

        }


        private void RenderContent(TextWriter writer)
        {
            RenderSummary(writer);
        }

        private void RenderSummary(TextWriter writer)
        {
            writer.Write("<p>This is your site's dashboard and control panel.</p>");
        }
    }
}